package server.core;

import server.*;
import server.util.RequestUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ApplicationDispatcher implements RequestDispatcher {
    private Wrapper wrapper = null;
    public ApplicationDispatcher(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    @Override
    public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        if (response.isCommitted())
            throw new IllegalStateException("响应已经提交");

        wrapper.invoke(new ForwardRequest((HttpServletRequest) request), new ForwardResponse((HttpServletResponse)response));

    }
    private class ForwardRequest implements HttpRequest {
        private HttpServletRequest request = null;
        public ForwardRequest(HttpServletRequest request) {
            this.request = request;
        }
        @Override
        public String getDecodedRequestURI() {
            return RequestUtil.URLDecode(request.getRequestURI());
        }

        @Override
        public void setPathInfo(String path) {

        }

        @Override
        public void setServletPath(String path) {

        }

        @Override
        public ServletRequest getRequest() {
            return request;
        }

        @Override
        public void setContext(Context context) {

        }
    }

    private class ForwardResponse implements HttpResponse {
        private HttpServletResponse response = null;
        public ForwardResponse(HttpServletResponse response) {
            this.response = response;
        }
        @Override
        public ServletResponse getResponse() {
            return response;
        }

        @Override
        public void setContext(Context context) {

        }

        @Override
        public Context getContext() {
            return null;
        }
    }
    @Override
    public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {

    }
}
